package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.fragment.InvestmentDetailFourFragment;
import com.wdh.kjs.fragment.InvestmentDetailOneFragment;
import com.wdh.kjs.fragment.InvestmentDetailThreeFragment;
import com.wdh.kjs.fragment.InvestmentDetailTwoFragment;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.DateUtilChange;
import com.wdh.kjs.util.ToastUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by DH on 2016/4/21.
 */
public class InvestmentDetailActivity extends BaseTopActivity implements View.OnClickListener {
    private TextView bt_id_introduction;
    private TextView bt_id_financing_person;
    private TextView bt_id_guarantee;
    private TextView bt_id_record;

    private FragmentManager manager;
    private FragmentTransaction transaction;
    private InvestmentDetailOneFragment fragmentOne;
    private InvestmentDetailTwoFragment fragmentTwo;
    private InvestmentDetailThreeFragment fragmentThree;
    private InvestmentDetailFourFragment fragmentFour;
    public static String itemId;
    private JsonModel jsonModel;
    private TextView tv_id_name;
    private TextView item_id_scale;
    private TextView item_id_month;
    private TextView item_id_financing_amount;
    private TextView tv_id_beginTime;
    private TextView tv_id_endTime;
    private TextView tv_id__available_amount;
    private ProgressBar tv_mifs_progressbar;
    private TextView tv_id_progress;
    private TextView tv_id_paymentMethod;
    private LinearLayout ii_invest_kefu;
    public static String m;
    public static int x;
    public static String l;
    public static String n;
    private String status;
    private String zhuangtai;
    private TextView tv_invest_now;
    private LinearLayout status_LinearLayout;
    private long day;
    private BigDecimal remain;
    private SharedPreferences sharedPreferences;
    public static String loginToken;
    public static String type;
    public static BigDecimal tate2;
    public static String ItemName;
    public static String InterestDays;
    private String partId;
    private LinearLayout ii_telephonr;
    private String gdItemType;
    private TextView tv_id__start_amount;
    private String increaseMoney;
    private String lowLimitMoney;
    private String levels;
    private String mytype;
    private String auditingOpinion="0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_investment_detail);
        itemId = getIntent().getStringExtra("itemId");
        status = getIntent().getStringExtra("status");
        zhuangtai = getIntent().getStringExtra("item_investment_state");
        Log.i("msg", zhuangtai + " " + status);
        sharedPreferences = getSharedPreferences("logininfo", MODE_PRIVATE);
        loginToken = sharedPreferences.getString("loginToken", "");
        levels = sharedPreferences.getString("levels", "");
//        mytype = sharedPreferences.getString("type", "");
        type = sharedPreferences.getString("type", "");
        if(type.equals("p")) {
            initshiming();
        }else if (type.equals("o")){
            initshimingorgnize();
        }
        initView();
        if (loginToken.equals("")) {
            tv_invest_now.setText("立即登录投资");
        }
        innitweb();
        initwidge();


    }
    private void initshimingorgnize() {
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();

//            params.addBodyParameter("emailAddress","742051747@qq.com" );
        params.addBodyParameter("partyId", loginToken);

        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_HUOQURENZHENG_O, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if(jsonModel.success) {
                    auditingOpinion=jsonModel.getRealAuthInfo().getAuditingOpinion();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });

    }
    private void initshiming() {
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();

//            params.addBodyParameter("emailAddress","742051747@qq.com" );
        params.addBodyParameter("partyId", loginToken);

        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_HUOQURENZHENG, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success)
                    auditingOpinion = jsonModel.getRealAuthInfo().getAuditingOpinion();
            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }
        });

    }
    private void initwidge() {
        if (zhuangtai.equals("抢购")) {

            tv_invest_now.setText("立即投资");
            tv_invest_now.setOnClickListener(this);
        } else if (status.equals("募集成功")) {
            status_LinearLayout.setBackgroundColor(getResources().getColor(R.color.background_gray));
//            tv_invest_now.setBackgroundResource(R.drawable.bt_style_gray_solid3);
            tv_invest_now.setText("已满标");
            tv_invest_now.setTextColor(getResources().getColor(R.color.font_gray_middle));

        } else if (status.equals("还款中")) {
            status_LinearLayout.setBackgroundColor(getResources().getColor(R.color.background_gray));
//            tv_invest_now.setBackgroundResource(R.drawable.bt_style_blue4);
            tv_invest_now.setText("还款中");
            tv_invest_now.setTextColor(getResources().getColor(R.color.colorPrimary));

        } else if (status.equals("还款完成")) {
            status_LinearLayout.setBackgroundColor(getResources().getColor(R.color.background_gray));
//            tv_invest_now.setBackgroundResource(R.drawable.bt_style_gray_solid3);
            tv_invest_now.setText("还款成功");
            tv_invest_now.setTextColor(getResources().getColor(R.color.font_gray_middle));

        } else if (status.equals("坏账")) {
            tv_invest_now.setVisibility(View.GONE);
        }
        ii_invest_kefu.setOnClickListener(this);
        ii_telephonr.setOnClickListener(this);
    }

    private void innitweb() {
        RequestParams params = new RequestParams();

        params.addBodyParameter("itemId", itemId);
        params.addBodyParameter("page", 1 + "");
        params.addBodyParameter("rows", "1");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Invest_DETAIL, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success) {

                    item();
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(InvestmentDetailActivity.this, "网络异常！");
            }
        });

    }

    private void item() {
        increaseMoney = jsonModel.getItemPlan().get(0).getIncreaseMoney();
        lowLimitMoney= jsonModel.getItemPlan().get(0).getLowLimitMoney();
        tv_id__start_amount.setText("￥" + lowLimitMoney+ "元");
        gdItemType = jsonModel.getItem().getGdItemType();
        partId = jsonModel.getItem().getPartyId();
        type = jsonModel.getItem().getType();
        remain = new BigDecimal(jsonModel.getItem().getTargetMoney().toString()).subtract(new BigDecimal(jsonModel.getItem().getRaiseMoney().toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
        day = jsonModel.getItem().getItemStartDate();
        if (zhuangtai.equals("预热中")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = new Date();

            String date=sdf.format(new java.util.Date());
            int remindDays = (int) ((day - d.getTime()) / 86400000 +1);
            if (remindDays < 0)
                tv_invest_now.setText("距投资开放还有" + 0 + "天");
            else
//            tv_invest_now.setText("距投资开放还有"+remindDays + "天");

                status_LinearLayout.setBackgroundColor(getResources().getColor(R.color.background_gray));
            tv_invest_now.setBackgroundResource(R.drawable.bt_style_blue4);
            tv_invest_now.setText("距投资开放还有" + remindDays + "天");
            tv_invest_now.setTextColor(getResources().getColor(R.color.colorPrimary));
//
        }
        BigDecimal bigDecimal = new BigDecimal(jsonModel.getItem().getTargetMoney() + "").setScale(2, RoundingMode.HALF_UP);
        ItemName = jsonModel.getItem().getItemName();
        tv_id_name.setText(ItemName);
        //   int tate2 = new BigDecimal(jsonModel.getItem().getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).intValue();
        tate2 = new BigDecimal(jsonModel.getItem().getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).setScale(2, BigDecimal.ROUND_HALF_UP);
        item_id_scale.setText(tate2 + "%");
        //   item_id_month.setText(jsonModel.getItem().getRaiseDays() + "天");
        InterestDays = jsonModel.getItem().getInterestDays();
        item_id_month.setText(InterestDays + "天");
        item_id_financing_amount.setText(bigDecimal + "元");
        String time = DateUtilChange.timestamp2String(jsonModel.getItem().getItemStartDate(), DateUtilChange.DEFAULT_DAY_FORMAT);
        String time1 = DateUtilChange.timestamp2String(jsonModel.getItem().getItemEndDate(), DateUtilChange.DEFAULT_DAY_FORMAT);
        tv_id_beginTime.setText(time);
        tv_id_endTime.setText(time1);
        DecimalFormat df = new DecimalFormat("0.00");
        BigDecimal rate = new BigDecimal(jsonModel.getItem().getTargetMoney() + "").subtract(new BigDecimal(jsonModel.getItem().getRaiseMoney() + ""));
        BigDecimal rate1 = new BigDecimal(jsonModel.getItem().getRaiseMoney() + "").divide(new BigDecimal(jsonModel.getItem().getTargetMoney() + ""), 2, RoundingMode.HALF_DOWN);
        BigDecimal percent = new BigDecimal(jsonModel.getItem().getRaiseMoney().toString()).divide(jsonModel.getItem().getTargetMoney(), 4, RoundingMode.HALF_UP).multiply(new BigDecimal(100 + ""));
//        BigDecimal percent = new BigDecimal(jsonModel.getItem().getRaiseMoney().toString()).divide(new BigDecimal(jsonModel.getItem().getTargetMoney().toString())).multiply(new BigDecimal(100 + ""));
        BigDecimal rate2 = new BigDecimal(percent + "").multiply(new BigDecimal(100 + "")).setScale(2, RoundingMode.HALF_UP);
        String newrate1 = df.format(percent);
        tv_mifs_progressbar.setProgress(percent.intValue());
        String str = df.format(rate);
        tv_id__available_amount.setText(str + "元");
        tv_id_progress.setText(newrate1 + "%");
        switch (jsonModel.getItem().getGdBenefitMode()) {
            case 0:
                m = "到期一次性还本付息";
                break;
            case 1:
                m = "按月付息到期还本";
                break;
        }
        tv_id_paymentMethod.setText(m);


    }

    private void initView() {
        initTopBar("项目详情");
        tv_id__start_amount = (TextView) findViewById(R.id.tv_id__start_amount);
        ii_telephonr = (LinearLayout) findViewById(R.id.ii_telephonr);
        ii_invest_kefu= (LinearLayout) findViewById(R.id.ii_invest_kefu);
        tv_invest_now = (TextView) findViewById(R.id.tv_invest_now);
        tv_id_paymentMethod = (TextView) findViewById(R.id.tv_id_paymentMethod);
        tv_id_progress = (TextView) findViewById(R.id.tv_id_progress);
        tv_mifs_progressbar = (ProgressBar) findViewById(R.id.tv_mifs_progressbar1);
        tv_id_endTime = (TextView) findViewById(R.id.tv_id_endTime);
        tv_id__available_amount = (TextView) findViewById(R.id.tv_id__available_amount);
        tv_id_beginTime = (TextView) findViewById(R.id.tv_id_beginTime);
        item_id_financing_amount = (TextView) findViewById(R.id.item_id_financing_amount);
        item_id_month = (TextView) findViewById(R.id.item_id_month);
        item_id_scale = (TextView) findViewById(R.id.item_id_scale);
        tv_id_name = (TextView) findViewById(R.id.tv_id_name);
        bt_id_introduction = (TextView) findViewById(R.id.bt_id_introduction);
        bt_id_financing_person = (TextView) findViewById(R.id.bt_id_financing_person);
        bt_id_guarantee = (TextView) findViewById(R.id.bt_id_guarantee);
        bt_id_record = (TextView) findViewById(R.id.bt_id_record);
//        tv_invest_now = (Button) findViewById(R.id.tv_invest_now);
        status_LinearLayout = (LinearLayout) findViewById(R.id.status_LinearLayout);
        bt_id_introduction.setOnClickListener(this);
        bt_id_financing_person.setOnClickListener(this);
        bt_id_guarantee.setOnClickListener(this);
        bt_id_record.setOnClickListener(this);
        bt_id_introduction.setTextColor(Color.parseColor("#5CACEE"));
        manager = getFragmentManager();
        transaction = manager.beginTransaction();
        fragmentOne = new InvestmentDetailOneFragment();
        transaction.add(R.id.ll_id_list, fragmentOne);
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        transaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.ii_telephonr:
//                Intent teleintent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:10010"));
//                startActivity(teleintent);
                Intent teleintent=new Intent(Intent.ACTION_DIAL);
                teleintent.setData(Uri.parse("tel:059183978755"));
                startActivity(teleintent);
                break;
            case R.id.bt_id_introduction:
                bt_id_introduction.setTextColor(Color.parseColor("#5CACEE"));
                bt_id_financing_person.setTextColor(Color.parseColor("#666666"));
                bt_id_guarantee.setTextColor(Color.parseColor("#666666"));
                bt_id_record.setTextColor(Color.parseColor("#666666"));
                fragmentOne = new InvestmentDetailOneFragment();
                transaction.replace(R.id.ll_id_list, fragmentOne, "fragmentOne");
                transaction.addToBackStack("fragmentOne");
                break;
            case R.id.bt_id_financing_person:
                bt_id_introduction.setTextColor(Color.parseColor("#666666"));
                bt_id_financing_person.setTextColor(Color.parseColor("#5CACEE"));
                bt_id_guarantee.setTextColor(Color.parseColor("#666666"));
                bt_id_record.setTextColor(Color.parseColor("#666666"));
                fragmentTwo = new InvestmentDetailTwoFragment();
                transaction.replace(R.id.ll_id_list, fragmentTwo, "fragmentTwo");
                transaction.addToBackStack("fragmentTwo");
                break;
            case R.id.bt_id_guarantee:
                bt_id_introduction.setTextColor(Color.parseColor("#666666"));
                bt_id_financing_person.setTextColor(Color.parseColor("#666666"));
                bt_id_guarantee.setTextColor(Color.parseColor("#5CACEE"));
                bt_id_record.setTextColor(Color.parseColor("#666666"));
                fragmentThree = new InvestmentDetailThreeFragment();
                transaction.replace(R.id.ll_id_list, fragmentThree, "fragmentThree");
                transaction.addToBackStack("fragmentThree");
                break;
            case R.id.bt_id_record:

                bt_id_introduction.setTextColor(Color.parseColor("#666666"));
                bt_id_financing_person.setTextColor(Color.parseColor("#666666"));
                bt_id_guarantee.setTextColor(Color.parseColor("#666666"));
                bt_id_record.setTextColor(Color.parseColor("#5CACEE"));
                fragmentFour = new InvestmentDetailFourFragment();
                transaction.replace(R.id.ll_id_list, fragmentFour, "fragmentFour");
                transaction.addToBackStack("fragmentFour");
                break;
            case R.id.tv_invest_now:
                if (tv_invest_now.getText().toString().equals("立即投资")) {
                    if (loginToken.equals("")) {
                        Intent intent = new Intent(this, LoginActivity.class);
                        intent.putExtra("state", "1");
                        startActivity(intent);
                    }else if (auditingOpinion.equals("0")) {
                        TipDialogShow("请先完成实名认证！");
                    }else if (partId.equals(loginToken)) {
                        TipDialogShow("不能投资自己的项目！");
                    } else if(type.equals("o")&&!levels.equals("3")){
                        TipDialogShow("未设置交易密码！");
                    } else if(type.equals("p")&&Integer.parseInt(levels)<2){
                        TipDialogShow("未设置交易密码！");
                    }else {
                        Intent it = new Intent(this, InvestPaymentActivity.class);
                        it.putExtra("itemId", itemId);
                        it.putExtra("remain", remain + "");
                        it.putExtra("gdItemType", gdItemType);
                        it.putExtra("increaseMoney", increaseMoney);
                        it.putExtra("lowLimitMoney", lowLimitMoney);
                        startActivity(it);
                    }
                }
//                InvestmentDetailActivity.this.finish();
                break;
            case R.id.ii_invest_kefu:
                startActivity(new Intent(this, FangKuiActivity.class));
                break;
        }
        transaction.commit();
    }


    private void TipDialogShow(String hint) {
        View dialog = View.inflate(this,R.layout.view_dialog_tip, null);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
    }
}
